package v3.chapter4.lockInterruptiblyTest2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Run {

	public static void main(String[] args) throws InterruptedException {
		final MyService service = new MyService();
		Runnable runnableRef = new Runnable() {
			@Override
			public void run() {
				service.waitMethod();
			}
		};
		
		Thread threadA = new Thread(runnableRef);
		threadA.setName("A");
		threadA.start();
		
		Thread.sleep(500);

		Thread threadB = new Thread(runnableRef);
		threadB.setName("B");
		threadB.start();
		threadB.interrupt();// 打标记
		
		System.out.println("main end!");
	}

}

class MyService{
	public ReentrantLock lock=new ReentrantLock();
	private Condition condition=lock.newCondition();
	
	public void waitMethod() {
		try {
			lock.lockInterruptibly();
			System.out.println("lock begin " + Thread.currentThread().getName());
			for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
				String newString = new String();
				Math.random();
			}
			System.out.println("lock   end " + Thread.currentThread().getName());
		}catch(InterruptedException e) {
			System.out.println("线程"+Thread.currentThread().getName()+"进入catch~!");
			e.printStackTrace(); 
		}finally {
			if(lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
	}
}